package com.lyc.common.interceptor;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jboss.marshalling.TraceInformation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lyc.common.constants.CommonConstants;
import com.lyc.common.constants.DepartCommonConstant;
import com.lyc.common.entity.UserInfo;
import com.lyc.common.exception.DepartException;
import com.lyc.common.holder.UserContextHolder;
import com.lyc.common.util.RedisCaching;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author 李大神仙
 * @Date 2024/2/28 20:31
 * @Version 1.0
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    //@Autowired
    //@Lazy
    //private DlFeign dlFeign;

    @Autowired
    private RedisCaching redisCaching;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //增加redis缓存
        String innerFlag = request.getHeader(CommonConstants.INNER_SERVICE);
        String authorization = request.getHeader(DepartCommonConstant.DLHeaderConstant.AUTHORIZATION);
        if (StringUtils.isEmpty(authorization) && CommonConstants.TRUE_STR.equals(innerFlag)){
            return true;
        }
        if (StringUtils.isEmpty(authorization)){
            throw new DepartException("500","缺少认证信息");
        }
        UserInfo userInfo = currentUserInfo(request);
        String language = request.getHeader("language");
        if (StringUtils.isNotBlank(language)){
            userInfo.setLanguage(language);
        }
        //登录用户的ip信息
        String clientIP = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(clientIP)){
            userInfo.setClientIP(clientIP);
        }else {
            userInfo.setIp(request.getRemoteAddr());
        }
        UserContextHolder.getInstance().setContext(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserContextHolder.getInstance().clear();
    }

    private UserInfo currentUserInfo(HttpServletRequest request){
        UserInfo userInfo = null;
        String requestURI = request.getRequestURI();
        log.info("请求地址:{}","请求的uri:{}",request.getRemoteAddr(),requestURI);
        String authorization = request.getHeader(DepartCommonConstant.DLHeaderConstant.AUTHORIZATION);
        if (StringUtils.isEmpty(authorization)){
            throw new DepartException("500","缺少认证信息");
        }
        String appCode = request.getHeader(DepartCommonConstant.DLHeaderConstant.ENCRYPTION_HEADER);
        String userLoginKey =
                DepartCommonConstant.RedisKeyPrefix.REDIS_USER_LOGIN_PREFIX +
                        authorization.replace(DepartCommonConstant.DLHeaderConstant.START_AUTHOTZIATION,"")+appCode;
        //表示通过点链请求
        if (authorization.toLowerCase().startsWith(DepartCommonConstant.DLHeaderConstant.START_AUTHOTZIATION)){
            String userInfoString = (String)redisCaching.get(userLoginKey);
            if (Objects.isNull(userInfoString)){
                userInfo = JSON.parseObject(userInfoString, UserInfo.class);
            }
        }
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setAppCode(appCode);
            UserInfoReq userInfoReq = new UserInfoReq();
            userInfoReq.setAppCode(appCode);
            userInfoReq.setQueryEnterpriseUserInfo(true);
            userInfoReq.setQueryEnterprise(true);
            userInfoReq.setQueryOrganization(true);
            userInfoReq.setQueryUserRole(true);
            try {
                //查询返回给UserInfo这个对象，然后再存储到缓存
                redisCaching.setEx(userLoginKey,JSON.toJSONString(userInfo),1800, TimeUnit.SECONDS);
            }catch (Exception e){
                throw new DepartException("500",e.getMessage());
            }
        }
        return userInfo;
    }
}


































